/**    
 * @{#} CommonUtility.java Create on 2013-10-18 上午11:16:24    
 *        
 * @author Evan
 *
 * @email evan0502@qq.com
 *
 * @version 1.0    
 */
package com.evan.common.utils;

import java.lang.ref.SoftReference;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.ui.OAlert;
import cn.skinapp.R;

import com.evan.common.connection.ConnectionCommon;
import com.evan.common.constant.Constant;

@SuppressLint({ "UseSparseArrays", "NewApi" })
public class CommonUtility {

	public static boolean isExistSDCard() {
		if (Environment.getExternalStorageDirectory().exists()) {
			return true;
		}
		return false;
	}

	public static void tip(Context context, int strRes) {
		tip(context, context.getString(strRes));
	}

	public static void tip(Context context, String str) {
		OAlert alert = new OAlert(context);
		alert.setOK("确认");
		alert.setTitle(str);
		alert.show();
	}

	public static HashMap<Integer, String> dayofweek;

	static {
		dayofweek = new HashMap<Integer, String>();
		dayofweek.put(1, "日");
		dayofweek.put(2, "一");
		dayofweek.put(3, "二");
		dayofweek.put(4, "三");
		dayofweek.put(5, "四");
		dayofweek.put(6, "五");
		dayofweek.put(7, "六");

	}

	public static final String PLATFORM = "Android";

	public static boolean isNull(Object o) {
		try {
			return null == o || "".equals(o.toString())
					|| "null".equals(o.toString());
		} catch (Exception e) {
		}
		return true;

	}

	public static View isEmpty(ArrayList<View> views, int position) {
		try {
			if (views.size() > 0 && views.get(position) != null) {
				return views.get(position);
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public static int dip2px(Context context, float dipValue) {
		float m = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * m + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		float m = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / m + 0.5f);
	}

	public static int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	public static ProgressDialog showWaitDialog(Context context) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(0);
		dialog.setTitle("更新");
		dialog.setMessage("正在下载最新版本...");
		dialog.setCancelable(false);
		dialog.show();
		return dialog;
	}

	public static void finish() {
		if (!CommonUtility.isNull(Constant.activitys)) {
			for (Activity activity : Constant.activitys.values()) {
				activity.finish();
			}
		}
	}

	public static void toast(Context context, String str) {
		try {
			Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
		}
	}

	public static void toast(Context context, int strRes) {
		try {
			Toast.makeText(context, context.getString(strRes),
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
		}
	}

	public static void toastLong(Context context, String str) {
		try {
			Toast.makeText(context, str, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
		}
	}

	public static void toastLong(Context context, int strRes) {
		try {
			Toast.makeText(context, context.getString(strRes),
					Toast.LENGTH_LONG).show();
		} catch (Exception e) {
		}
	}

	public static void setListViewItemBG(View view, int position) {
		if (position % 2 != 0) {
			view.setBackgroundResource(R.drawable.list_item_2);
		} else {
			view.setBackgroundResource(R.drawable.list_item_1);
		}
	}

	public static boolean serviceIsRunning(Context context, String packageName) {
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Activity.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> mServiceList = mActivityManager
				.getRunningServices(100);
		for (RunningServiceInfo service : mServiceList) {
			if (packageName.equals(service.service.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	public static HashMap<String, Object> params(String[] key, Object[] objects) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		for (int i = 0; i < key.length; i++) {
			params.put(key[i], objects[i]);
		}
		return params;
	}

	public static int matchIndex(Object[] objs, Object currentStr) {
		if (!CommonUtility.isNull(objs)) {
			for (int i = 0; i < objs.length; i++) {
				Object o = objs[i];
				if (o.toString().equals(currentStr.toString())) {
					return i;
				}
			}
		}
		return -1;
	}

	public static boolean isSuccess(JSONObject o) {
		try {
			if (!CommonUtility.isNull(o)) {
				return Constant.RESPONSE_SUCCESS.equals(o.getString("status"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String getInfo(JSONObject o) {
		try {
			if (!CommonUtility.isNull(o)) {
				return o.getString("info");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static JSONArray getJsonArray(JSONObject o) {
		try {
			return o.getJSONArray("result");
		} catch (Exception e) {
		}
		return new JSONArray();
	}

	/**
	 * 获取版本名称
	 * 
	 * @return 当前应用的版本名称
	 */
	public static String getVersion(Context context) {
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(),
					0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public static int getVersionCode(Context context) {
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(),
					0);
			int version = info.versionCode;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	public static Matrix convertMartix(String filePath) {
		Matrix matrix = new Matrix();
		try {
			ExifInterface exifInterface = new ExifInterface(filePath);
			if (CommonUtility.isNull(exifInterface)) {
				return matrix;
			}
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_UNDEFINED);
			switch (orientation) {
			case ExifInterface.ORIENTATION_UNDEFINED:
				break;
			case ExifInterface.ORIENTATION_NORMAL:
				break;
			case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
				matrix.postScale(-1f, 1f);
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				matrix.postRotate(180f);
				break;
			case ExifInterface.ORIENTATION_FLIP_VERTICAL:
				matrix.postScale(1f, -1f);
				break;
			case ExifInterface.ORIENTATION_ROTATE_90:
				matrix.postRotate(90f);
				break;
			case ExifInterface.ORIENTATION_TRANSVERSE:
				matrix.postRotate(-90f);
				matrix.postScale(1f, -1f);
				break;
			case ExifInterface.ORIENTATION_TRANSPOSE:
				matrix.postRotate(90f);
				matrix.postScale(1f, -1f);
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				matrix.postRotate(-90f);
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return matrix;
	}

	public static Dialog logout(final Context context, OnClickListener l) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		return builder.setTitle("退出").setMessage("是否确定退出？")
				.setNegativeButton("取消", null).setPositiveButton("确定", l)
				.show();
	}

	public static void finishActivityFromName(String className) {
		Activity activity = Constant.activitys.get(className);
		try {
			if (!CommonUtility.isNull(activity) && !activity.isFinishing()) {
				activity.finish();
				Constant.activitys.remove(className);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * return 2012-01-01; method desc：
	 * 
	 * @return
	 */
	public static String getCurrentDate() {
		return new Timestamp(System.currentTimeMillis()).toString().substring(
				0, 10);
	}

	/**
	 * return 2012-01-01; method desc：
	 * 
	 * @return
	 */
	public static String getCurrentDate(int start, int end) {
		return new Timestamp(System.currentTimeMillis()).toString().substring(
				start, end);
	}

	/**
	 * 计算两个日期相差的天数 method desc：
	 * 
	 * @param startTime
	 * @param endTime
	 * @param format
	 */
	@SuppressLint("SimpleDateFormat")
	public static long dateDiff(String startTime, String endTime, String format) {
		// 按照传入的格式生成一个simpledateformate对象
		SimpleDateFormat sd = new SimpleDateFormat(format);
		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
		long diff;
		try {
			// 获得两个时间的毫秒时间差异
			diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
			long day = diff / nd;// 计算差多少天
			// 输出结果
			return day;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * return 2012-01-01 10:10; method desc：
	 * 
	 * @return
	 */
	public static String getCurrentDateFormat(String format) {
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault());
		return df.format(date);
	}

	/**
	 * return 2012-01-01 10:10; method desc：
	 * 
	 * @return
	 */
	public static String getCurrentDateWithHourMin() {
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-M-d HH:mm",
				Locale.getDefault());
		return df.format(date);
	}

	public static String formatDate(String date, int start, int end) {
		try {
			return date.replace("T", " ").substring(start, end);
		} catch (Exception e) {
			return null;
		}
	}

	public static String formatDateSession(String date, int start, int end) {
		return date.substring(start, end);
	}

	public static String formateDate(int year, int month, int day) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		StringBuilder sb = new StringBuilder();
		sb.append(year).append("年");
		if (month < 9) {
			sb.append(0);
		}
		sb.append(month + 1);
		sb.append("月");
		if (day < 10) {
			sb.append(0);
		}
		sb.append(day);
		sb.append("日").append(" 周")
				.append(dayofweek.get(cal.get(Calendar.DAY_OF_WEEK)));
		return sb.toString();
	}

	/**
	 * 
	 * method desc：
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @return 组织年月日，用-连接
	 */
	public static String formateDateWithWenzi(int year, int month, int day) {
		StringBuilder sb = new StringBuilder();
		sb.append(year).append("-");
		if (month < 9) {
			sb.append(0);
		}
		sb.append(month + 1).append("-");
		if (day < 10) {
			sb.append(0);
		}
		sb.append(day);
		return sb.toString();
	}

	/**
	 * 
	 * method desc：
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @return 组织年月日，用-连接
	 */
	public static String formateDateWithWenzi(int year, int month, int day,
			int hour, int min) {
		StringBuilder sb = new StringBuilder();
		sb.append(year).append("-");
		sb.append(month + 1).append("-");
		sb.append(day).append(Constant.SPACE);
		if (hour < 10) {
			sb.append(0);
		}
		sb.append(hour).append(":");
		if (min < 10) {
			sb.append(0);
		}
		sb.append(min);
		return sb.toString();
	}

	public static String formateDateWithoutWeek(int year, int month, int day) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		StringBuilder sb = new StringBuilder();
		sb.append(year).append("-");
		if (month < 9) {
			sb.append(0);
		}
		sb.append(month + 1);
		sb.append("-");
		if (day < 10) {
			sb.append(0);
		}
		sb.append(day);
		return sb.toString();
	}

	public static String formateDateWithWeek(int year, int month, int day) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		StringBuilder sb = new StringBuilder();
		sb.append(year).append("-");
		if (month < 9) {
			sb.append(0);
		}
		sb.append(month + 1);
		sb.append("-");
		if (day < 10) {
			sb.append(0);
		}
		sb.append(day);
		sb.append(" 周").append(dayofweek.get(cal.get(Calendar.DAY_OF_WEEK)));
		return sb.toString();
	}

	public static String formateDateWithHour(int year, int month, int day,
			int hour, int minute) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		StringBuilder sb = new StringBuilder();

		sb.append(year).append("年");
		if (month < 9) {
			sb.append(0);
		}
		sb.append(month + 1);
		sb.append("月");
		if (day < 10) {
			sb.append(0);
		}
		sb.append(day);
		sb.append("日").append(" 周")
				.append(dayofweek.get(cal.get(Calendar.DAY_OF_WEEK)))
				.append(" ").append(hour).append(":").append(minute);

		return sb.toString();
	}

	public static String deviceInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append(Build.MODEL).append("@@").append(Build.VERSION.RELEASE);
		return sb.toString();
	}

	public static int indexOf(Activity activity, View view) {
		ViewGroup rootView = (ViewGroup) activity.getWindow().getDecorView();
		return rootView.indexOfChild(view);
	}

	public static void addView(Activity activity, View view, int anim) {
		ViewGroup rootView = (ViewGroup) activity.getWindow().getDecorView();
		rootView.addView(view);
		if (anim > 0) {
			view.startAnimation(AnimationUtils.loadAnimation(activity, anim));
		}
	}

	public static void removeView(final Activity activity, final View view,
			int anim) {
		if (!CommonUtility.isNull(view)) {
			Animation animation = AnimationUtils.loadAnimation(activity, anim);
			animation.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {

				}

				@Override
				public void onAnimationRepeat(Animation animation) {

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					ViewGroup rootView = (ViewGroup) activity.getWindow()
							.getDecorView();
					rootView.removeView(view);
				}
			});
			view.startAnimation(animation);

		}
	}

	public static void removeView(Activity activity, View view) {
		if (!CommonUtility.isNull(view)) {
			ViewGroup rootView = (ViewGroup) activity.getWindow()
					.getDecorView();
			rootView.removeView(view);
		}
	}

	public static void hideKeyboard(Activity activity, View view) {
		InputMethodManager imm = (InputMethodManager) activity
				.getApplicationContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
		// 显示或者隐藏输入法
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	public static void showKeyboard(final View view) {
		Timer timer = new Timer();

		timer.schedule(new TimerTask() {
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) view
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(view, 0);
			}
		}, 150);

	}

	static Dialog networkDialog;

	/**
	 * 
	 * method desc：
	 * 
	 * @param context
	 * @param l
	 */
	public static void tipNetworkWithOperate(final Activity context,
			final Class<?> clazz, OnClickListener l) {
		if (!CommonUtility.isNull(networkDialog) && networkDialog.isShowing()) {
			networkDialog.dismiss();
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		networkDialog = builder.setTitle("提醒").setMessage("检测到当前网络未连接，请确认网络。")
				.setNegativeButton("重新登录", new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						Intent intent = new Intent(context, clazz);
						context.startActivity(intent);
						CommonUtility.finish();
						context.finish();
					}
				}).setPositiveButton("退出", new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						CommonUtility.finish();
						context.finish();
					}
				}).show();
		networkDialog.setCancelable(false);
	}

	static int[] WI = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

	static String[] VALIDATENUM = { "1", "0", "X", "9", "8", "7", "6", "5",
			"4", "3", "2" };

	public static boolean cardValidate(String cardNum) {
		if (!CommonUtility.isNull(cardNum)) {
			if (cardNum.length() != 18) {
				return false;
			}
			int count = 0;
			for (int i = 0; i < cardNum.length() - 1; i++) {
				count += Integer.parseInt(cardNum.substring(i, i + 1)) * WI[i];
			}
			int mod = count % 11;
			String validateNum = VALIDATENUM[mod];
			if (!validateNum.equals(cardNum.substring(17))) {
				return false;
			}
		}
		return true;
	}

	public static String[] generatArr(int min, int max, boolean isBuZero) {
		String[] strs = new String[max];
		for (int i = min; i < max; i++) {
			if (isBuZero) {
				strs[i] = i < 10 ? "0" + i : i + "";
			} else {
				strs[i] = i + "";
			}
		}
		return strs;
	}

	public static Bitmap getBitmapCache(Object key) {
		SoftReference<Bitmap> reference = Constant.imagesCache.get(key
				.toString());
		Bitmap bitmap = null;
		if (!CommonUtility.isNull(reference)) {
			bitmap = reference.get();
		}
		if (!CommonUtility.isNull(bitmap) && !bitmap.isRecycled()) {
			return bitmap;
		} else {
			return null;
		}
	}

	// screen shot current activity
	public static Bitmap takeScreenShot(Activity activity, View v) {
		View view = v;
		if (CommonUtility.isNull(v)) {
			view = activity.getWindow().getDecorView();
		}

		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap b1 = view.getDrawingCache();

		// get the height of status bar
		// Rect frame = new Rect();
		// activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		// int statusBarHeight = frame.top;
		// Log.i("log", "" + statusBarHeight);

		// int width =
		// activity.getWindowManager().getDefaultDisplay().getWidth();
		// int height = activity.getWindowManager().getDefaultDisplay()
		// .getHeight();
		Bitmap b = Bitmap.createBitmap(b1, 0, (int) view.getY(),
				view.getWidth(), view.getHeight());
		view.destroyDrawingCache();
		return b;
	}

	public static void putAll(JSONArray dst, JSONArray src) {
		try {
			for (int i = 0; i < src.length(); i++) {
				dst.put(src.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static JSONArray removeItem(JSONArray src, JSONObject removeItem) {
		JSONArray array = new JSONArray();
		try {
			for (int i = 0; i < src.length(); i++) {
				JSONObject object = src.getJSONObject(i);
				if (object != removeItem) {
					array.put(object);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return array;
	}

	/**
	 * Get the screen height.
	 * 
	 * @param context
	 * @return the screen height
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public static int getScreenHeight(Activity context) {

		Display display = context.getWindowManager().getDefaultDisplay();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			Point size = new Point();
			display.getSize(size);
			return size.y;
		}
		return display.getHeight();
	}

	/**
	 * Get the screen width.
	 * 
	 * @param context
	 * @return the screen width
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public static int getScreenWidth(Activity context) {

		Display display = context.getWindowManager().getDefaultDisplay();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			Point size = new Point();
			display.getSize(size);
			return size.x;
		}
		return display.getWidth();
	}

	public static Bitmap rotate(Bitmap bitmap, int degree) {
		if (bitmap.getHeight() < bitmap.getWidth()) {
			Matrix matrix = new Matrix();
			matrix.postRotate(degree);

			Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), matrix, true);
			return b;
		} else {
			return bitmap;
		}
	}

	/**
	 * 验证邮箱地址是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}

		return flag;
	}

	/**
	 * 验证手机号码
	 * 
	 * @param mobiles
	 * @return [0-9]{5,9}
	 */
	public static boolean isMobileNO(String mobiles) {
		boolean flag = false;
		try {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(mobiles);
			flag = m.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public static boolean isNum(String number) {
		boolean flag = false;
		try {
			Pattern p = Pattern.compile("^[0-9]{5}$");
			Matcher m = p.matcher(number);
			flag = m.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public static SpannableString convertSpannableString(Context context,
			int res, String content) {
		Drawable drawable = context.getResources().getDrawable(res);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		SpannableString spannable = new SpannableString(content + "[icon]");
		ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
		spannable.setSpan(span, content.length(),
				content.length() + "[icon]".length(),
				Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		return spannable;
	}

	public static SpannableString convertSpannableStringWithPrix(
			Context context, int res, String content) {
		Drawable drawable = context.getResources().getDrawable(res);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		SpannableString spannable = new SpannableString(content);
		ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
		spannable.setSpan(span, content.indexOf("[icon]"),
				content.indexOf("[icon]") + "[icon]".length(),
				Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		return spannable;
	}

	public static String getAge(String birthday) {
		if (!CommonUtility.isNull(birthday)) {
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int birthday_year = Integer.parseInt(birthday.substring(0, 4));
			return String.valueOf(year - birthday_year);
		}
		return "0";
	}

	public static String getClientName(Context context) {
		String client = context.getPackageName().substring(
				context.getPackageName().lastIndexOf(".") + 1);
		return client;
	}

	public static boolean isValidNetWord(Context context) {
		return ConnectionCommon.getInstance().checkNetwork(context);
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	public static boolean isZh(Context context) {
		Locale locale = context.getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		if (language.endsWith("zh"))
			return true;
		else
			return false;
	}

	public static void setImageIdentityTag(View view, Object object) {
		view.setTag(R.id.tag_obj_image_identity, object);
	}

	public static void setViewHolderTag(View view, Object object) {
		view.setTag(R.id.tag_obj_viewholder, object);
	}

	public static Object getViewHolderTag(View view) {
		return view.getTag(R.id.tag_obj_viewholder);
	}

	public static void freshListImage(Object o, View view, Object identity) {
		Bitmap bitmap = (Bitmap) o;
		if (!CommonUtility.isNull(bitmap)) {
			if (!CommonUtility.isNull(view.getTag(R.id.tag_obj_image_identity))
					&& view.getTag(R.id.tag_obj_image_identity).toString()
							.equals(identity.toString())) {
				// ((ImageLayout) view).setImageBitmap(bitmap);
			}
		}
	}

	public static String getDBData(ArrayList<CacheCommon> caches) {
		if (caches.size() > 0) {
			return caches.get(0).data;
		}
		return "";
	}

	public static void putAll(ArrayList<Object> list, JSONArray src,
			boolean addObject) {
		try {
			JSONObject object = null;
			for (int i = 0; i < src.length(); i++) {

				object = src.getJSONObject(i);

				if (addObject) {
					list.add(object);
				} else {
					ArrayList<String> ids = new ArrayList<String>();

					for (Object item : list) {
						ids.add(new JSONObject(item.toString()).getJSONObject(
								"QuestionSearch").getString("Qid"));
					}

					if (!ids.contains(object.getJSONObject("QuestionSearch")
							.getString("Qid"))) {
						list.add(object);
					}

				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public static void putAll(ArrayList<Object> list, ArrayList<Object> src) {
		list.addAll(src);
	}

	public static SharedPreferences getSharedPreferences(Context context) {
		return context.getSharedPreferences(Constant.SHAREPREFERENCE, 0);
	}

	/**
	 * 
	 * method desc： 根据年月获取当月最大天数
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getMaxDay(int year, int month) {
		Calendar c = Calendar.getInstance();
		c.set(year, month, 1);
		c.add(Calendar.DAY_OF_YEAR, -1);
		return c.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 卸载广播 method desc：
	 * 
	 * @param activity
	 * @param receiver
	 */
	public static void unRegisteReciver(Activity activity,
			BroadcastReceiver receiver) {
		try {
			if (receiver != null) {
				activity.unregisterReceiver(receiver);
			}
		} catch (Exception e) {
		}
		receiver = null;
	}

	public static String getText(TextView textView) {
		return textView.getText().toString();
	}

	public static String getText(EditText editText) {
		return editText.getText().toString();
	}

	/**
	 * 根据时间返回 刚刚，1分钟前-59分钟前，1小时前-23小时前，昨天，前天，4天前-90天前，3个月前，04-20。 method desc：
	 * 
	 * @param date
	 * @return
	 */
	public static String getTimeDiff(String date, int start, int end) {
		if (date == null || date.trim().equals("")) {
			return "";
		}
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.getDefault());
		DateFormat format2 = new SimpleDateFormat("HH:mm", Locale.getDefault());
		Date d = null;

		try {
			d = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();

		}

		Calendar cal = Calendar.getInstance();
		long diff = 0;
		Date dnow = cal.getTime();
Calendar curCal = Calendar.getInstance();
curCal.setTimeInMillis(d.getTime());
		long currentData = cal.getTimeInMillis();

		long current = d.getTime() - currentData;

		String str = "";
		if (dnow != null && d != null)
			diff = dnow.getTime() - d.getTime();

		if (diff > 2678400000L) {
			str = date.substring(start, end);
		} else if (diff > 2592000000L) {// 30 * 24 * 60 * 60 * 1000=2592000000
										// 毫秒
			str = "1个月前";
		} else if (diff > 1814400000) {// 21 * 24 * 60 * 60 * 1000=1814400000 毫秒
			str = "3周前";
		} else if (diff > 1209600000) {// 14 * 24 * 60 * 60 * 1000=1209600000 毫秒
			str = "2周前";
		} else if (diff > 604800000) {// 7 * 24 * 60 * 60 * 1000=604800000 毫秒
			str = "1周前";
		} else if (diff > 86400000) { // 24 * 60 * 60 * 1000=86400000 毫秒
			int day = (int) Math.floor(diff / 86400000f);
			if (day == 1) {
				str = "昨天" + format2.format(d);
			} else if (day == 2) {
				str = "前天" + format2.format(d);
			} else {
				str = // day + "天前"
				format.format(d);
			}
		} else if (diff > 3600000) {// 60 * 60 * 1000=18000000 毫秒
			str = // (int) Math.floor(diff / 3600000f) + "小时前"
			format2.format(d);

		//	if (current < 0) {
			if(curCal.get(Calendar.DAY_OF_MONTH)==cal.get(Calendar.DAY_OF_MONTH))
				str = "昨天" + format2.format(d);
		//	}

		} else if (diff > 60000) {// 1 * 60 * 1000=60000 毫秒
			str = // (int) Math.floor(diff / 60000) + "分钟前"
			format2.format(d);
		} else if (diff < -1) {
			str = "";
		} else {
			str = "刚刚";
		}
		return str;
	}

}
